package Redis;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.resps.Tuple;

import java.util.Set;

public class rdo {
    private Jedis jedis;
    private static final String CAR_POSITION_FORMAT = "car:%s:position";
    private static final String OBSTACLE_KEY = "map:obstacle";

    //连接功能
    public void connect(String host, int port) {
        try {
            jedis = new Jedis(host, port);
            System.out.println("✅ Redis连接成功");
            System.out.println("Ping响应: " + jedis.ping());
        } catch (Exception e) {
            System.out.println("连接失败！");
        }
    }

    //获取地图宽度
    public int getMapWidth() {
        String width = jedis.get("mapwidth");
        return width == null ? 0 : Integer.parseInt(width);
    }

    // 获取地图高度
    public int getMapHeight() {
        String height = jedis.get("mapheight");
        return height == null ? 0 : Integer.parseInt(height);
    }

    //获取小车数量
    public int getCarcount()
    {
        String count=jedis.get("carcount");
        return count==null?0:Integer.parseInt(count);
    }

    //获取静态地图
    public String getMapObstacle() {
        String mapobstacle = jedis.get(OBSTACLE_KEY);
        if (mapobstacle == null) {
            System.err.println("❌ 障碍物数据为空");
            return null;
        }
        int count = getCarcount();
        int width = getMapWidth();
        // 使用 StringBuilder 支持修改
        StringBuilder obstacleBuilder = new StringBuilder(mapobstacle);

        for (int i = 1; i <= count; i++) {
            Position car = loadCarPosition(String.valueOf(i));
            if (car != null) {
                int index = car.y * width + car.x;
                if (index >= 0 && index < obstacleBuilder.length()) {
                    obstacleBuilder.setCharAt(index, '0');  // 将小车位置置为 0
                } else {
                    System.err.println("⚠️ 小车坐标超出障碍物矩阵范围: " + car);
                }
            }
        }
        return obstacleBuilder.toString();  // 返回处理后的障碍物字符串
    }

    //获取zadd这个列表，按照score从小到大进行排序了
    public Set<Tuple> getZSetWithScores(String key) {
        return (Set<Tuple>) jedis.zrangeWithScores(key, 0, -1);
    }
    // 获取车辆当前位置
    private Position loadCarPosition(String carId) {
        String key = String.format(CAR_POSITION_FORMAT, carId);
        String xStr = jedis.hget(key, "x");
        String yStr = jedis.hget(key, "y");

        if (xStr == null || yStr == null) return null;

        try {
            int x = Integer.parseInt(xStr);
            int y = Integer.parseInt(yStr);
            return new Position(x, y);
        } catch (NumberFormatException e) {
            System.out.println("小车位置数据异常");
            return null;
        }
    }

    // 坐标结构体
    private static class Position {
        int x, y;

        Position(int x, int y) {
            this.x = x;
            this.y = y;
        }

        @Override
        public String toString() {
            return x + " " + y;
        }
    }

}
